package cn.mulanbay.auth.controller;

import cn.mulanbay.api.system.bean.RemoteWxAuthAccessUrl;
import cn.mulanbay.api.system.service.RemotePaymentService;
import cn.mulanbay.api.system.service.RemoteUserService;
import cn.mulanbay.auth.bean.response.UserInfoVo;
import cn.mulanbay.auth.bean.response.WechatLoginUrlVo;
import cn.mulanbay.business.handler.CacheHandler;
import cn.mulanbay.business.handler.PasswordHandler;
import cn.mulanbay.common.bean.ResultBean;
import cn.mulanbay.common.config.CacheKey;
import cn.mulanbay.persistent.entity.User;
import cn.mulanbay.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 微信登录
 *
 * @author fenghong
 * @create 2022-01-16 10:00
 */
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    /**
     * 授权登录URl实效时间（秒）
     */
    @Value("${wx.state.expires:300}")
    private int stateExpires;

    @Autowired
    CacheHandler cacheHandler;

    @Autowired
    PasswordHandler passwordHandler;

    @Autowired
    RemotePaymentService remotePaymentService;

    @Autowired
    RemoteUserService remoteUserService;

    /**
     * 获取登录URL
     *
     * @return
     */
    @RequestMapping(value = "/authAccessUrl", method = RequestMethod.GET)
    public ResultBean authAccessUrl() {
        RemoteWxAuthAccessUrl aau = remotePaymentService.authAccessUrl().getData();
        WechatLoginUrlVo vo = new WechatLoginUrlVo();
        vo.setUrl(aau.getUrl());
        vo.setState(aau.getStat());
        vo.setExpires(stateExpires);
        return callback(vo);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public ResultBean userInfo(String state) {
        String userKey = CacheKey.getKey(CacheKey.WX_AUTH_STATE_USER,state);
        Long userId = cacheHandler.get(userKey,Long.class);
        UserInfoVo vo = new UserInfoVo();
        if(userId==null){
            return callback(vo);
        }
        User user = remoteUserService.getUser(userId).getData();
        String pwd = passwordHandler.decodePassword(user.getPassword());
        vo.setUsername(user.getUsername());
        vo.setPassword(pwd);
        return callback(vo);
    }


}
